﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.Json.Serialization;
using System.Text.Json;
using System.Threading.Tasks;
using Share;

namespace Share.Converts
{
    internal class SortedConverter : JsonConverter<object>
    {
        public override bool CanConvert(Type typeToConvert)
        {
            return true; // 这里简化处理，实际使用时应根据需要判断
        }

        public override IcbcApiRequest? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            throw new NotImplementedException();
        }

        public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
        {
            writer.WriteStartObject();
            var properties = typeof(IcbcApiRequest)
                .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .Select(p => new
                {
                    Property = p,
                    JsonPropertyName = p.GetCustomAttribute<JsonPropertyNameAttribute>()?.Name ?? p.Name
                })
                .OrderBy(x => x.JsonPropertyName);

            foreach (var prop in properties)
            {
                writer.WritePropertyName(prop.JsonPropertyName);
                JsonSerializer.Serialize(writer, prop.Property.GetValue(value), options);
            }

            writer.WriteEndObject();
        }
    }
}
